package com.xiaoxiong.mami.config;

import com.xiaoxiong.mami.http.AppJsonResult;
import com.xiaoxiong.mami.http.ResultCode;
import com.xiaoxiong.mami.service.TokenService;
import com.xiaoxiong.mami.utils.PrintWriterUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Administrator on 2017/8/9.
 */
@Component
public class UserSecurityInterceptor implements HandlerInterceptor {

    @Autowired
    TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if(!tokenService.checkTokenIsVailByTokenStr(token)){
            PrintWriterUtil.print(response,new AppJsonResult(ResultCode.TOKEN_INVALID_CODE, "token已过期", null).toResult());
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
